/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cedict.parser;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.cedict.domain.CedictRowDefinition;
import org.cedict.domain.UTF8CedictRow;
import org.geergenbein.parser.LineParser;
import org.geergenbein.parser.ParserException;

/**
 *
 * @author Andrew
 */
public class UTF8CedictLineParser implements LineParser<UTF8CedictRow> {

    private final static String FIELD_SEPARATOR = " ";
    private final static String PINYIN_START = "[";
    private final static String ESCAPED_PINYIN_START =
            PINYIN_START.replace(PINYIN_START, "\\" + PINYIN_START);
    private final static String PINYIN_END = "]";
    private final static String ESCAPED_PINYIN_END =
            PINYIN_END.replace(PINYIN_END, "\\" + PINYIN_END);
    private final static String DEFINITION_SEPARATOR = "/";
    private final static Pattern LINE_REGEX =
            Pattern.compile(
            "^(\\S+)" + FIELD_SEPARATOR +
            "(\\S+)" + FIELD_SEPARATOR + ESCAPED_PINYIN_START +
            "([^" + PINYIN_END + "]+)" + ESCAPED_PINYIN_END +
            FIELD_SEPARATOR +
            DEFINITION_SEPARATOR + "(.*)" + DEFINITION_SEPARATOR + "$");

    public UTF8CedictRow parse(String line) {
        UTF8CedictRow cedictRow = null;
        Matcher m = LINE_REGEX.matcher(line);
        if (m.matches()) {
            String traditional = m.group(1);
            String simplified = m.group(2);
            String pinyin = m.group(3);
            List<String> definitions = new ArrayList<String>();
            for (String definition : m.group(4).split("/")) {
                definitions.add(definition);
            }
            cedictRow = new UTF8CedictRow(traditional, simplified, pinyin,
                    definitions);
        } else {
            throw new ParserException("Failed to parse line '" + line + "' " +
                    "with regex '" + LINE_REGEX.toString() + "'");
        }
        return cedictRow;
    }

    public String toString(UTF8CedictRow cedictRow) {
        List<String> definitions = new ArrayList<String>();
        for (CedictRowDefinition def : cedictRow.getDefinitions()) {
            definitions.add(def.getDefinition());
        }
        return cedictRow.getTraditionalCharacters() + FIELD_SEPARATOR +
                cedictRow.getSimplifiedCharacters() + FIELD_SEPARATOR +
                PINYIN_START + cedictRow.getPinyin() + PINYIN_END +
                FIELD_SEPARATOR + DEFINITION_SEPARATOR +
                StringUtils.join(definitions,
                DEFINITION_SEPARATOR) + DEFINITION_SEPARATOR;
    }
}
